package com.findyou.interceptors;

import com.findyou.pojo.Result;
import com.findyou.utils.JwtUtil;
import com.findyou.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @Title: LoginInterceptor
 * @Author 贾金博
 * @Package com.findyou.interceptors
 * @Date 2024/3/9 14:53
 * @description:
 */

@Component
@CrossOrigin
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal里面
            ThreadLocalUtil.set(claims);
            return true; // 放行
        } catch (Exception e) {
            response.setStatus(401); // 状态码
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空数据 防止内存泄露
        ThreadLocalUtil.remove();
    }
}
